package com.st.swagger.service;

import com.st.swagger.entity.User;
import com.st.swagger.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取所有用户
     */
    public List<User> getAllUsers() {
        return userMapper.findAll();
    }

    /**
     * 根据用户 ID 获取用户详情
     */
    public User getUserById(Long id) {
        User user = userMapper.findById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return user;
    }

    /**
     * 注册新用户
     */
    public void registerUser(User user) {
        if (userMapper.existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        userMapper.insertUser(user);
    }

    /**
     * 用户登录
     */
    public User loginUser(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null || !user.getPassword().equals(password)) {
            throw new RuntimeException("用户名或密码错误");
        }
        return user;
    }

    /**
     * 更新用户信息
     */
    public User updateUser(Long id, User user) {
        User existingUser = userMapper.findById(id);
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }
        user.setId(id);
        userMapper.updateUser(user);
        return user;
    }

    /**
     * 删除用户
     */
    public void deleteUser(Long id) {
        User existingUser = userMapper.findById(id);
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }
        userMapper.deleteUser(id);
    }
}

